import React, { useState, useRef, useEffect } from 'react';

import PieDoughnutChart from 'src/components/Chart/PieDoughnut';
import LineStackChart from 'src/components/Chart/LineStackChart';
import FilterTool from '../../../components/FilterTool';
import services from 'src/services/api';
import { Row, Col, Radio } from 'antd';
import moment from 'moment';

export default function ChallengeStatistics(props) {
  const [datas, setDatas] = useState({ winner: {}, challenger: {} });
  const [pieDatas, setPieDatas] = useState({ winner: {}, challenger: {} });
  const [group, setGroup] = useState([]);
  const [winner, setWinner] = useState([]);
  const [challenger, setChallenger] = useState([]);
  const [statType, setStatType] = useState('trend'); // 统计类型 trend:趋势 cycle:占比
  const [initParams, setInitParams] = useState(null)

  const queryParam = useRef(null);
  const statTypeParam = useRef({ stat_type: 'trend' });
  useEffect(() => {
    getChallengeGroupInfo();
  }, []);

  const strategy_id = props.strategy_id
  const api = props.api || 'produce' // 不同模块下存在相同的接口

  function getChallengeGroupInfo() {
    services[api].challengeGroupInfo({ strategy_id }).then((res) => {
      if (res.code === 0) {
        setGroup(res.data);
      }
    });
  }
  function freshQueryList(params) {}

  function refreshFilter(params, type) {
    queryParam.current = params;
    if (type === false) return
    getStatistics();
  }
  function getStatistics() {
    if (
      !queryParam.current.group ||
      !queryParam.current.winner ||
      !queryParam.current.challenger ||
      !queryParam.current.type ||
      !queryParam.current.start ||
      !queryParam.current.end ||
      !statTypeParam.current.stat_type
    ) {
      return;
    }
    services[api].challengeCompare({ strategy_id, ...queryParam.current, ...statTypeParam.current }).then((res) => {
      if (res.code === 0) {
        statTypeParam.current.stat_type === 'trend' ? setDatas(res.data) : setPieDatas(res.data);
      }
    });
  }
  function handleChangeGroup(key, value) {
    const currentGroup = group.find((it) => it.group === value);
    setWinner(currentGroup ? currentGroup.winner : []);
    setChallenger(currentGroup ? currentGroup.challenger : []);
    setInitParams({ group: value, winner: (currentGroup ? currentGroup.winner[0].value : ''), challenger: (currentGroup ? currentGroup.challenger[0].value : '') })
    window.setTimeout(() => {
      setInitParams(null)
    }, 0)
  }

  function changeStatType(e) {
    statTypeParam.current = { stat_type: e.target.value };
    setStatType(e.target.value);
    getStatistics();
  }

  const filter = [
    {
      label: '节点名称',
      labelStyle: { width: '60px' },
      type: 'select',
      key: 'group',
      name: 'group',
      placeholder: '请选择',
      span: 12,
      allowClear: true,
      style: { marginBottom: '10px' },
      options: [
        ...group.map((item) => {
          return {
            value: item.group,
            name: item.group,
          };
        }),
      ],
      onChange: handleChangeGroup,
    },
    {
      label: '对比项',
      labelStyle: { width: '60px', paddingLeft: '20px' },
      type: 'select',
      key: 'winner',
      name: 'winner',
      placeholder: '请选择',
      span: 6,
      allowClear: true,
      style: { marginBottom: '10px' },
      options: [
        ...winner.map((item) => {
          return {
            value: item.value,
            name: item.name,
          };
        }),
      ],
    },
    {
      label: 'VS',
      labelStyle: { width: '20px' },
      type: 'select',
      key: 'challenger',
      name: 'challenger',
      placeholder: '请选择',
      span: 6,
      allowClear: true,
      style: { marginBottom: '10px' },
      options: [
        ...challenger.map((item) => {
          return {
            value: item.value,
            name: item.name,
          };
        }),
      ],
    },
    {
      label: '对比内容',
      labelStyle: { width: '60px' },
      type: 'select',
      key: 'type',
      name: 'type',
      placeholder: '事件执行结果',
      span: 12,
      defaultValue: 1,
      allowClear: true,
      style: { marginBottom: '10px' },
      options: [{ value: 1, name: '事件执行结果' }],
    },
    {
      label: '对比时间',
      labelStyle: { width: '60px', paddingLeft: '20px' },
      type: 'rangepicker',
      key: 'start',
      name: ['start', 'end'],
      span: 12,
      defaultValue: [
        moment()
          .subtract(7, 'day')
          .startOf('day')
          .format('YYYY-MM-DD HH:mm:ss'),
        moment().format('YYYY-MM-DD HH:mm:ss'),
      ],
      disabledDate: (current) => {
        return current && (current > moment().endOf('day') || current < moment().subtract(40, 'days'));
      },
      ranges: {
        本周: [moment().startOf('week'), moment()],
        近7天: [moment().subtract('days', 6), moment()],
        本月: [moment().startOf('month'), moment()],
        近30天: [moment().subtract('days', 29), moment()],
      },
      format: 'YYYY-MM-DD HH:mm:ss',
      placeholder: ['起始时间', '结束时间'],
      allowClear: false,
      style: { marginBottom: '10px' },
    },
  ];

  const colors = ['#1890ff', 'rgb(33, 209, 180)', 'rgb(247, 129, 32)', 'rgb(247, 76, 33)'];

  const formatterInit = (params, total) => {
    let str = `${params.seriesName}<br/>`
    str = str + params.marker + params.name + "：" + params.value + ' (' + (params.value / total).toFixed(1) * 100 + '%)'
    return str
  }

  const lineStack = () => {
    const winnerData =
      (datas.winner &&
        datas.winner.data &&
        datas.winner.data.map((it, index) => {
          const color = colors[index];
          it.name = datas.winner.name + it.name;

          return {
            ...it,
            itemStyle: {
              normal: {
                color: color,
                lineStyle: {
                  width: 2,
                  type: 'solid', //'dotted'虚线 'solid'实线
                },
              },
            },
          };
        })) ||
      [];
    const challengerData =
      (datas.challenger &&
        datas.challenger.data &&
        datas.challenger.data.map((it, index) => {
          const color = colors[index];
          it.name = datas.challenger.name + it.name;
          return {
            ...it,
            itemStyle: {
              normal: {
                color: color,
                lineStyle: {
                  width: 2,
                  type: 'dotted', //'dotted'虚线 'solid'实线
                },
              },
            },
          };
        })) ||
      [];
    const data = [...winnerData, ...challengerData];
    return (
      <>
        {data.length > 0 && (
          <LineStackChart
            id='data'
            width='100%'
            height='400px'
            dataSource={data}
            xRender={(it) => it.index}
            dataRender={(it) => it.requests}
            legendSetting={{
              width: 600,
              height: 150,
            }}
          />
        )}
      </>
    );
  };

  const pieStack = () => {
    const winnerData = pieDatas.winner;
    const challengerData = pieDatas.challenger;
    return (
      <>
        {challengerData.total !== undefined &&
          (winnerData.total !== undefined && (
            <Row gutter={30}>
              <Col span={12}>
                {winnerData.total > 0 ? (
                  <PieDoughnutChart
                    id='winnerData'
                    width='100%'
                    height='400px'
                    dataSource={winnerData.data}
                    total={{
                      title: winnerData.name,
                      value: '',
                      y: '150px'
                    }}
                    tooltipFormatter={(params) => formatterInit(params, winnerData.total)}
                  />
                ) : (
                  '暂无数据'
                )}
              </Col>
              <Col span={12}>
                {challengerData.total > 0 ? (
                  <PieDoughnutChart
                    id='challengerData'
                    width='100%'
                    height='400px'
                    dataSource={challengerData.data}
                    total={{
                      title: challengerData.name,
                      value: '',
                      y: '150px'
                    }}
                    tooltipFormatter={(params) => formatterInit(params, challengerData.total)}
                  />
                ) : (
                  '暂无数据'
                )}
              </Col>
            </Row>
          ))}
      </>
    );
  };
  return (
    <div>
      <FilterTool
        data={filter}
        colNum={2}
        query={freshQueryList}
        refreshFilter={refreshFilter}
        isOnChange={true}
        isSearchNotSpaceBetween={true}
        gutter={20}
        initParams={initParams}
      />

      <Row type='flex' justify='space-between'>
        <Col span={16}>
          <div style={{ marginTop: '20px' }}>{statType === 'trend' ? lineStack() : pieStack()}</div>
        </Col>
        <Col span={6}>
          <Radio.Group onChange={changeStatType} value={statType}>
            <Row type='flex' style={{ marginTop: '30px', marginBottom: '10px' }}>
              <Col>
                <Radio value={'trend'} />
                <span style={{ marginRight: '12px' }}>请求量：</span>
              </Col>
              <Col>
                总请求量
                <br />
                通过请求量
                <br />
                复核请求量
                <br />
                拒绝请求量
              </Col>
            </Row>
            <Row type='flex'>
              <Col>
                <Radio value={'cycle'} />
                请求占比：
              </Col>
              <Col>
                通过请求占比
                <br />
                复核请求占比
                <br />
                拒绝请求占比
                <br />
                其他请求占比
              </Col>
            </Row>
          </Radio.Group>
        </Col>
      </Row>
    </div>
  );
}
